import React, { useState, useEffect, useRef } from 'react';
import { useQuery, useMutation, useQueryClient } from 'react-query';
import { Users } from 'api/queries';
import { setAccountTrialPeriod } from 'api/mutations';

const ApiLogEvent = ({ event, onClose }) => {
  if (!event) return null;
  
  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-lg p-6 w-full max-w-3xl max-h-[80vh] overflow-auto">
        <div className="flex justify-between items-center mb-4">
          <h2 className="text-xl font-bold text-blue-700">
            {event.type === 'request' ? '⬆️ API Request' : '⬇️ API Response'}
          </h2>
          <button 
            className="text-gray-500 hover:text-gray-700 focus:outline-none"
            onClick={onClose}
          >
            ✕
          </button>
        </div>
        
        {event.type === 'request' && (
          <div className="mb-4 bg-blue-50 p-4 rounded border border-blue-200">
            <div className="font-semibold text-blue-800">Request Details</div>
            <div className="mt-2">
              <span className="inline-block bg-blue-600 text-white text-xs px-2 py-1 rounded mr-2">
                {event.method?.toUpperCase() || 'GET'}
              </span>
              <span className="font-mono text-sm">{event.url || 'Unknown URL'}</span>
            </div>
            {event.data && (
              <div className="mt-3">
                <div className="text-sm text-blue-700 font-medium">Request Body:</div>
                <pre className="bg-white p-3 rounded border border-blue-100 text-xs mt-1 overflow-auto">
                  {JSON.stringify(event.data, null, 2)}
                </pre>
              </div>
            )}
          </div>
        )}
        
        {event.type === 'response' && (
          <div>
            <div className="mb-4 bg-green-50 p-4 rounded border border-green-200">
              <div className="font-semibold text-green-800">Response Details</div>
              <div className="mt-2 flex items-center">
                <span className={`inline-block text-white text-xs px-2 py-1 rounded mr-2 ${
                  event.status >= 200 && event.status < 300 ? 'bg-green-600' : 'bg-red-600'
                }`}>
                  {event.status || '???'}
                </span>
                <span className="font-mono text-sm">{event.statusText || 'Unknown Status'}</span>
              </div>
            </div>
            
            <div className="mb-4">
              <div className="text-sm font-medium mb-1">Response Data:</div>
              <pre className="bg-gray-100 p-4 rounded overflow-auto text-xs">
                {JSON.stringify(event.data, null, 2)}
              </pre>
            </div>
            
            {event.headers && (
              <div className="mb-4">
                <div className="text-sm font-medium mb-1 flex items-center">
                  <span>Response Headers</span>
                  <span className="ml-2 text-xs text-gray-500">(click to expand)</span>
                </div>
                <details>
                  <summary className="cursor-pointer text-xs text-blue-600 hover:text-blue-800">
                    Show Headers
                  </summary>
                  <pre className="bg-gray-100 p-4 rounded overflow-auto text-xs mt-2">
                    {JSON.stringify(event.headers, null, 2)}
                  </pre>
                </details>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

const SimpleTrialRefreshPage = () => {
  const [selectedUserId, setSelectedUserId] = useState('');
  const [selectedAccountId, setSelectedAccountId] = useState('');
  const [apiEvents, setApiEvents] = useState([]);
  const [currentEvent, setCurrentEvent] = useState(null);
  const queryClient = useQueryClient();
  const isMounted = useRef(true);
  
  // Add API events to our log
  const logApiEvent = (event) => {
    setApiEvents(prev => [...prev, event]);
    setCurrentEvent(event);
  };
  
  // Clear current event popup
  const clearCurrentEvent = () => {
    setCurrentEvent(null);
  };
  
  // Handle Users query with API logging
  const { data: axiosResponse, isLoading, error } = useQuery('AllUsers', Users, {
    onSuccess: (data) => {
      if (isMounted.current) {
        // Log API response event
        logApiEvent({
          type: 'response',
          url: data.config?.url || '/users/',
          status: data.status,
          statusText: data.statusText,
          data: data.data,
          headers: data.headers,
          timestamp: new Date().toISOString()
        });
      }
    },
    onError: (err) => {
      if (isMounted.current) {
        // Log API error event
        logApiEvent({
          type: 'response',
          url: '/users/',
          status: err.response?.status || 500,
          statusText: err.response?.statusText || err.message,
          data: err.response?.data || { error: err.message },
          timestamp: new Date().toISOString()
        });
      }
    }
  });
  
  // Log initial API request event when the component mounts
  useEffect(() => {
    isMounted.current = true;
    
    // Log the initial API request
    logApiEvent({
      type: 'request',
      method: 'GET',
      url: '/users/',
      timestamp: new Date().toISOString()
    });
    
    return () => {
      isMounted.current = false;
    };
  }, []);
  
  // Extract the actual users array from the Axios response
  const usersArray = axiosResponse?.data || [];
  
  const handleUserChange = (event) => {
    const userId = event.target.value;
    setSelectedUserId(userId);
    
    // Find the selected user's account ID
    if (userId && usersArray.length > 0) {
      const user = usersArray.find(u => u.id === userId);
      if (user && user.accountId) {
        setSelectedAccountId(user.accountId);
      } else {
        setSelectedAccountId('');
      }
    } else {
      setSelectedAccountId('');
    }
  };
  
  // Mutation for setting trial period with API logging
  const setTrialMutation = useMutation(
    ({ accountId, days }) => {
      // Log API request event
      const requestData = { trialDays: days };
      const requestUrl = `/accounts/${accountId}/trial`;
      
      logApiEvent({
        type: 'request',
        method: 'PUT',
        url: requestUrl,
        data: requestData,
        timestamp: new Date().toISOString()
      });
      
      return setAccountTrialPeriod(accountId, days);
    },
    {
      onSuccess: (data) => {
        // Log API response event
        logApiEvent({
          type: 'response',
          url: data.config?.url || `/accounts/${selectedAccountId}/trial`,
          status: data.status,
          statusText: data.statusText,
          data: data.data,
          headers: data.headers,
          timestamp: new Date().toISOString()
        });
        
        // Reset selection and refetch users
        setSelectedUserId('');
        setSelectedAccountId('');
        queryClient.invalidateQueries('AllUsers');
      },
      onError: (err) => {
        // Log API error event
        logApiEvent({
          type: 'response',
          url: `/accounts/${selectedAccountId}/trial`,
          status: err.response?.status || 500,
          statusText: err.response?.statusText || err.message,
          data: err.response?.data || { error: err.message },
          timestamp: new Date().toISOString()
        });
      }
    }
  );
  
  const handleRefreshTrial = () => {
    if (selectedAccountId) {
      // Set trial period to 3 days
      setTrialMutation.mutate({ accountId: selectedAccountId, days: 3 });
    }
  };
  
  // View API log history
  const showApiLogHistory = () => {
    alert(`API Log History (${apiEvents.length} events):\n\n${
      apiEvents.map(event => 
        `${event.timestamp} - ${event.type.toUpperCase()} ${event.method || ''} ${event.url} ${event.status || ''}`
      ).join('\n')
    }`);
  };
  
  if (isLoading) return (
    <div className="flex justify-center items-center h-screen">
      <div className="text-xl font-semibold">Loading users...</div>
    </div>
  );
  
  if (error) return (
    <div className="flex justify-center items-center h-screen">
      <div className="text-xl font-semibold text-red-500">Error loading users: {error.message}</div>
    </div>
  );
  
  return (
    <div className="flex flex-col items-center justify-center min-h-screen bg-gray-50">
      <div className="bg-white p-8 rounded-lg shadow-lg w-full max-w-md">
        <h1 className="text-2xl font-bold text-center mb-6">Refresh User Trial</h1>
        
        <div className="mb-6">
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Select User
          </label>
          <select
            className="block w-full px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
            value={selectedUserId}
            onChange={handleUserChange}
            disabled={isLoading || setTrialMutation.isLoading}
          >
            <option value="">Select a user</option>
            {usersArray && usersArray.length > 0 ? (
              usersArray.map(user => (
                <option key={user.id} value={user.id}>
                  {user.email}
                </option>
              ))
            ) : (
              <option disabled>No users available</option>
            )}
          </select>
        </div>
        
        <div className="flex justify-center">
          <button 
            className="px-6 py-3 bg-blue-600 text-white font-medium rounded-md shadow hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
            disabled={!selectedAccountId || setTrialMutation.isLoading}
            onClick={handleRefreshTrial}
          >
            {setTrialMutation.isLoading ? 'Refreshing...' : 'Refresh Trial (3 Days)'}
          </button>
        </div>
        
        <div className="mt-6 flex justify-center">
          <button
            className="text-sm text-blue-600 hover:text-blue-800 focus:outline-none"
            onClick={showApiLogHistory}
          >
            Show API Log History ({apiEvents.length})
          </button>
        </div>
      </div>
      
      {/* API Event Popup */}
      {currentEvent && (
        <ApiLogEvent 
          event={currentEvent}
          onClose={clearCurrentEvent}
        />
      )}
    </div>
  );
};

export default SimpleTrialRefreshPage;